<template>
	<section>
		<!--工具条-->
		<el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
			<el-form :inline="true" :model="search">
				<el-form-item>
					<el-input v-model="search.key" placeholder="关键词"></el-input>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" v-on:click="queryData">查询</el-button>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" @click="handleAdd">新增</el-button>
				</el-form-item>
        <el-form-item>
        <el-button type="primary" @click="handleFile">导入Excel</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleExportFile">导出Excel</el-button>
        </el-form-item>
			</el-form>
		</el-col>

		<!--列表-->
		<el-table :data="pageInfo.data" highlight-current-row v-loading="listLoading" @selection-change="selsChange" style="width: 100%;">
      <el-table-column type="selection" width="55">
      </el-table-column>
      <el-table-column type="index" width="60">
      </el-table-column>
      <el-table-column prop="username" label="管理者账号" width="120" sortable>
      </el-table-column>
      <el-table-column prop="password" label="管理者密码" width="120" sortable>
      </el-table-column>
      <el-table-column prop="email" label="电子邮箱" width="180" sortable>
      </el-table-column>
      <el-table-column prop="phone" label="电话" width="180" sortable>
      </el-table-column>
      <el-table-column prop="age" label="年龄" width="120" sortable>
      </el-table-column>
      <el-table-column prop="sex" label="性别" width="120" sortable>
      </el-table-column>
      <el-table-column prop="state" label="状态" width="120" sortable>
        <template slot-scope="scope">
          <span v-if="scope.row.state==-1" style="color: dodgerblue">未激活</span>
          <span v-else-if="scope.row.state==1" style="color: green">已激活</span>
          <span v-else-if="scope.row.state==2" style="color: orangered;">锁定</span>
          <span v-else-if="scope.row.state==3" style="color: red;">注销</span>
          <span v-else style="color: red">驳回</span>
        </template>
      </el-table-column>

      <el-table-column label="操作" width="300">
        <template scope="scope">
          <el-button size="small" @click="handleSave(scope.$index, scope.row)">编辑</el-button>
          <el-button type="danger" size="small" @click="handleDel(scope.$index, scope.row)">删除</el-button>
          <el-button type="primary" size="small" @click="handleRole(scope.$index, scope.row)">设置角色</el-button>
        </template>
      </el-table-column>
		</el-table>

		<!--工具条-->
		<el-col :span="24" class="toolbar">
			<el-button type="danger" @click="batchRemove" :disabled="this.sels.length===0">批量删除</el-button>
      <!--
          el-pagination 表示分页
          @size-change : 每页条数改变的时候会触发的方法
          @current-change: 当页数改变的时候
          :current-page: 绑定当前页数据
          :page-sizes="[100, 200, 300, 400]" : 每页多少条的选择
          :page-size="100" 每页的条数
          :total="400" 总条数
          layout="total, sizes, prev, pager, next, jumper"
     -->
      <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="search.currentPage"
          :page-sizes="[10, 20]"
          :page-size="100"
          style="float: right"
          layout="total, sizes, prev, pager, next, jumper"
          :total="pageInfo.total">
      </el-pagination>

		</el-col>

    <!--设置角色界面-->
    <el-dialog title="设置角色" :visible.sync="roleFormVisible" :close-on-click-modal="false">
      <el-form :model="rolesForm" label-width="80px" ref="addForm">
        <el-form-item label="员工名称" prop="name">
          <el-input v-model="rolesForm.username" disabled auto-complete="off"></el-input>
        </el-form-item>
        <!--
         :props="props" 定义前端显示的数据 与 对象 属性是匹配的
         :data="data" 绑定数据源，也就是查出来的权限树
         default-expand-all 默认展开
         ref="tree" 给树形控件取一个名字
       -->
        <el-form-item label="角色" prop="name">
          <el-tree
              :props="props"
              :data="roleData"
              default-expand-all
              node-key="id"
              ref="tree"
              show-checkbox
          >
          </el-tree>
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click.native="roleFormVisible = false">取消</el-button>
        <el-button type="primary" @click.native="employeeRole" >提交</el-button>
      </div>
    </el-dialog>


    <!--导入excel界面-->
    <!-- action="/api/employee/excel" 传到后台的请求-->
    <!--    :headers="tokenHeader"  设置上传的请求头-->
    <!--    :file-list="fileList"  上传的文件列表-->
    <el-dialog title="导入员工Exel" :visible.sync="fileVisible" :close-on-click-modal="false">
      <el-upload
          class="upload-demo"
          action="/api/employee/excel"
          :on-preview="handlePreview"
          :on-remove="handleRemove"
          :before-remove="beforeRemove"
          :on-success="handleSuccess"
          :on-error="handleError"
          multiple
          :limit="3"
          :on-exceed="handleExceed"
          :file-list="fileList"
          :headers="tokenHeader">
        <el-button size="small" type="primary">点击上传</el-button>
        <!--        <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>-->
      </el-upload>
    </el-dialog>

		<!--新增和修改界面-->
		<el-dialog title="新增" :visible.sync="saveFormVisible" :close-on-click-modal="false">
			<el-form :model="saveForm" label-width="80px" ref="addForm">
        <el-form-item label="员工账号" prop="username">
          <el-input v-model="saveForm.username" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="员工密码" prop="password">
          <el-input v-model="saveForm.password" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="电子邮箱" prop="email">
          <el-input v-model="saveForm.email" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="头像" prop="headImage">
          <el-input v-model="saveForm.headImage" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="员工年龄" prop="age">
          <el-input v-model="saveForm.age" auto-complete="off"></el-input>
        </el-form-item>
        <!--:options="deptTree":后台查出来的父部门即其子部门数据
            :props="{  自定义规则
            label:'name' 显示的为部门名
        -->
        <el-form-item label="所属部门">
          <el-cascader v-model="saveForm.department"
                       :options="deptTree"
                       :props="{
							   checkStrictly: true,
							   label:'name',
							   value:'id'
							}"
                       clearable></el-cascader>
        </el-form-item>

			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button @click.native="saveFormVisible = false">取消</el-button>
				<el-button type="primary" @click.native="addSubmit" >提交</el-button>
			</div>
		</el-dialog>
	</section>
</template>

<script>

	export default {
		data() {
			return {

        fileList: [],
        fileVisible:false,
        tokenHeader: {"token": sessionStorage.getItem("token")},


        roleData:[],
        props: {
          label: 'name',
          children: 'children'
        },
        roleFormVisible:false, //设置角色弹框默认关闭
        rolesForm:{},

        deptTree:[],  //后台查出来的父部门即其子部门数据

        search: {
          key: '',
          pageSize:10,
          currentPage:1
        },
        pageInfo:{
          data: [],
          total: 0,
        },

				listLoading: false,
				sels: [],//列表选中列

       saveFormVisible:false,
        saveForm:{
          id:null,
          username:"",
          password:"",
          email:"",
          headImage:"",
          department:{
            id:null,
            name:"",
          }
        }

			}
		},
		methods: {

      //点击设置角色按钮
      handleRole(index,row){
        this.roleFormVisible=true;
        this.rolesForm.id = row.id;
        this.rolesForm.username = row.username;
        this.getRoleTree();
        this.getRoleIds();
      },
      //获取角色树
      getRoleTree(){
        //发送请求
        this.$http.get("/role").then(res => {
          if (res.data.success) {
            this.roleData = res.data.data;
          } else {
            this.$message.error("获取角色列表失败");
          }
        }).catch(res => {
          this.$message.info("网络异常");
        });
      },

      getRoleIds() {
        this.$http.get("/employee/role/" + this.rolesForm.id).then(res => {
          if (res.data.success) {
            this.$refs.tree.setCheckedKeys(res.data.data);
          } else {
            this.$message.error("回显失败");
          }
        }).catch(res => {
          this.$message.info("网络异常");
        });
      },

      employeeRole() {
        this.rolesForm.list = this.$refs.tree.getCheckedKeys();
        this.$http.put("/employee/role", this.rolesForm).then(result => {
          if (result.data.success) {
            this.$message.success("绑定成功");
          } else {
            this.$message.error("绑定失败");
          }
        }).catch(result => {
          this.$message.info("网络异常");
        });
        this.roleFormVisible = false;
      },

		  //点击导出excel
      handleExportFile() {
        this.$confirm('确定导出员工表吗?', '提示', {
          type: 'warning'
        }).then(() => { //点击确定
          //this.$http.post(url,data,config) 将key设置在headers，而headers需要设置在config里面
          this.$http.post("/employee/exportExcel",{} ,{headers: {'key': this.search.key}}).then(res => {
            if (res.data.success) {
              this.$message.success("导出成功");
            } else {
              this.$message.error("导出失败");
            }
          }).catch(res => {
            this.$message.info("网络异常");
          });
        }).catch(() => { //点击取消
          this.$message.info('已取消');
        });
      },

      handleExceed(files, fileList) {
        this.$message.warning(`当前限制选择 3 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`);
      },
      handleError(err, file, fileList) {
      },
      handleSuccess(response, file, fileList) {
        if (response.success) {
          this.$message.success("导入成功!");
        } else {
          this.$message.warning("部分数据异常!");
          console.log(response.data);
        }
        this.refreshEmployee();
        this.fileVisible = false;
      },

      beforeRemove(file, fileList) {
        return this.$confirm(`确定移除 ${file.name}？`);
      },
      handleRemove(file, fileList) {
        console.log(file, fileList);
      },
      handlePreview(file) {
        console.log(file);
      },
      //刷新员工页面
      refreshEmployee() {
        this.search.currentPage = 1;
        this.getEmployees();
      },

      //点击导入excel
      handleFile() {
        this.fileVisible = true;
      },


      //获取部门树
      getDeptTree(){
        //发送请求
        this.$http.get("/department/deptTree")
            .then(res =>{
              res = res.data
              if(res.success){
                this.deptTree = res.data;
              }
            })
            .catch(res =>{})
      },

      // 点击新增
      handleAdd(){
        this.saveFormVisible = true; //显示弹出框
        this.saveForm= {
          id:null,
          username:"",
          password:"",
          email:"",
          headImage:"",
          department:{
            id:null,
            name:"",
          }
        }
        //调用查询部门树的方法
        this.getDeptTree();
      },

      // 点击查询的方法
      queryData(){
        this.search.currentPage = 1
        this.getEmployees()
      },

      // 每页条数变动的时候
      handleSizeChange(val) {
        console.log(`每页 ${val} 条`);
        this.search.pageSize = val
        this.getEmployees()
      },

			//性别显示转换
			formatSex: function (row, column) {
				return row.sex == 1 ? '男' : row.sex == 0 ? '女' : '未知';
			},

			handleCurrentChange(val) {
        // val 指的是当前的页数
        this.search.currentPage = val;
        this.getEmployees();
			},

      //获取用户列表
      getEmployees() {
        this.listLoading=true;
        this.$http.post("/employee",this.search)
            .then(res=>{
              this.listLoading=false;
              res = res.data;
              console.log(res)
              if(res.success){
                // this.departments = res.data.data
                // this.total = res.data.total
                this.pageInfo = res.data //将查出的数据总数和数据赋给pageInfo，进而给列表传数据并显示
              }
            })
            .catch(res=>{})
        // this.listLoading = true;

      },

			//删除
      handleDel: function (index, row) {
        this.$confirm('确认删除该记录吗?', '提示', {
          type: 'warning'
        }).then(() => {  //点击确认
          this.listLoading = true;
          this.$http.delete("/employee/"+row.id)  //发送删除请求，并传id
              .then(res=>{
                res = res.data
                this.listLoading = false;  //加载框消失
                if(res.success){
                  this.$message({type:"success",message:"删除成功"});
                }else{
                  this.$message.error("删除失败"+res.msg)
                }
                this.search.currentPage= 1; //删完回到第一页
                this.getEmployees();  //重新查询
              })
              .catch(res=>{})

        }).catch(() => {

        });
      },


			//显示新增和修改界面
			handleSave: function (index,row) {
				this.saveFormVisible = true;
        console.log(row);
        this.saveForm = JSON.parse(JSON.stringify(row)); //数据回显,深拷贝
        //所属部门回显
        var split = row.department.path.split("/");
        console.log(split)
        var data = []
        for (let i = 1; i < split.length; i++) {
          data.push(Number.parseInt(split[i]))
        }
        console.log(data)
        this.saveForm.department = data;

        //判断所属部门 是否为空
        // if(!row.department){
        //   this.saveForm.department={
        //     id:null,
        //     name:""
        //   }
        // }


        //调用查询部门树的方法
        this.getDeptTree();
			},


			//新增和修改的提交按钮
			addSubmit: function () {
				this.$refs.addForm.validate((valid) => {
					if (valid) {
						this.$confirm('确认提交吗？', '提示', {}).then(() => {

							//NProgress.start();
							let para = Object.assign({}, this.saveForm); //获取输入框的值

              //判断所属部门
              var depart = para.department;
              if (depart.length >= 0){
                if (depart.length==0){
                  para.department={id:null,name:""}
                }else{
                  para.department={id:depart[depart.length-1],name:""}
                }
              }

							//发送请求
              this.$http.put("/employee",para)
              .then(res =>{
                this.saveFormVisible = false; //关闭弹出框
                this.$message({type:"success",message:"保存成功"});
                this.getEmployees() //重新查询
              })
              .catch(res =>{

              })

						});
					}
				});
			},
			selsChange: function (sels) {
				this.sels = sels;
			},

			//批量删除
			batchRemove: function () {
				var ids = this.sels.map(item => item.id);
				this.$confirm('确认删除选中记录吗？', '提示', {
					type: 'warning'
				}).then(() => { //点击确认
					this.listLoading = true;
          //发送请求
          this.$http.patch("/employee",ids)  //发送删除请求，并传id
              .then(res=>{
                res = res.data
                this.listLoading = false;  //加载框消失
                if(res.success){
                  this.$message({type:"success",message:"删除成功"});
                }else{
                  this.$message.error("删除失败"+res.msg)
                }
                this.search.currentPage= 1; //删完回到第一页
                this.getEmployees();  //重新查询
              })
              .catch(res=>{})

				}).catch(() => {

				});
			}
		},
		mounted() {
			this. getEmployees();
		}
	}

</script>

<style scoped>

</style>